package com.doubao.wechat.interceptor;

import com.doubao.common.utils.RedisTemplateFactory;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * OAuth State 验证拦截器
 */
@Slf4j
public class OAuthStateInterceptor implements HandlerInterceptor {
    private final RedisTemplate<String, Object> redisTemplate;

    public OAuthStateInterceptor() {
        this.redisTemplate = RedisTemplateFactory.getRedisTemplate();
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String state = request.getParameter("state");

        // 检查 state 是否为空
        if (state == null) {
            log.warn("OAuth 回调 state 为空");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid state");
            return false;
        }

        // 验证 state 是否存在且有效
        Object cachedState = redisTemplate.opsForValue().get("oauth:state:" + state);
        if (cachedState == null) {
            log.warn("OAuth state 验证失败：{}", state);
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid state");
            return false;
        }

        // 验证通过后删除 state，防止重放攻击
        redisTemplate.delete("oauth:state:" + state);

        return true;
    }
}